package niu.toy.spring.mvc.impl;

import niu.toy.spring.mvc.HandlerExecutionChain;
import niu.toy.spring.mvc.HandlerInterceptor;
import niu.toy.spring.mvc.HandlerMapping;
import niu.toy.spring.mvc.HandlerMethod;
import niu.toy.spring.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据请求查找Action Handler(请求执行的方法)
 * @author niu
 */
public class HandlerMappingFinder implements HandlerMapping {

    private static final Logger logger = LoggerFactory.getLogger(HandlerMappingFinder.class);

    private final Map<String, HandlerMethod> mappingRegistry = new LinkedHashMap<>();
    private final List<HandlerInterceptor> interceptors = new ArrayList<>();
    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        HandlerMethod handler = getHandlerInternal(request);
        if (handler == null) {
            return null;
        }

        HandlerExecutionChain chain = new HandlerExecutionChain(handler);
        interceptors.forEach(interceptor->chain.addInterceptor(interceptor));
        return chain;
    }

    protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
        String lookupPath = WebUtil.getRequestPath(request);
        if (logger.isDebugEnabled()) {
            logger.debug("Looking up handler method for path " + lookupPath);
        }
        return mappingRegistry.get(lookupPath+":"+request.getMethod().toUpperCase());
    }
    public void registerMapping( Map<String, HandlerMethod> mappingRegistry) {
        this.mappingRegistry.putAll(mappingRegistry);
    }
}
